package com.example.teachermgt.controller;

import com.example.teachermgt.model.Teacher;
import com.example.teachermgt.service.TeacherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class TeacherController {
    private final static Logger log = LoggerFactory.getLogger(TeacherController.class);
    @Resource
    private TeacherService teacherService;

    @GetMapping("/ping")
    public String ping() {
        log.info("ping");
        return "pong";
    }

    @GetMapping("/queryAll")
    public List<Teacher> queryAll() {
        log.info("queryAll");
        List<Teacher> lists = teacherService.queryAll();
        return lists;
    }

    @PostMapping("/teacher")
    public Teacher teacher() {
        log.info("create a teacher");
        return teacherService.create();
    }

    @GetMapping("/cachedTeacherById")
    public Teacher cachedTeacherById(@RequestParam Long id) {
        try {
            log.info("find cached teacher by id");
            Teacher teacher = teacherService.cachedTeacherById(id);
            return teacher;
        } catch (Exception e) {
            log.error("find cached teacher failed: " + id);
            return null;
        }
    }

    @GetMapping("/findTeacherById")
    public Teacher findTeacherById(@RequestParam Long id) {
        try {
            log.info("find teacher by id");
            return teacherService.findTeacherById(id);
        } catch (Exception e) {
            log.error("find teacher failed: {},{}", id, e);
            return null;
        }
    }

    @PostMapping("/updateTeacher")
    public String updateTeacher(@RequestBody Teacher teacher) {
        log.info("updateTeacher");
        int result = teacherService.updateTeacher(teacher);
        if (result != 0) {
            return "update teacher success";
        }
        log.error("update teacher failed");
        return "failed";
    }

    @DeleteMapping("/deleteTeacherById")
    public String deleteTeacherById(@RequestParam Long id) {
        log.info("delete teacher by id");
        int result = teacherService.deleteTeacherById(id);
        if (result != 0) {
            return "delete success";
        }
        log.error("delete teacher failed");
        return "delete failed";
    }
}
